/**
 * @class yijs.air.view
 * @fileOverview sqlite数据库操作类
 * @author 谢文浩
 * @email mohaiguyan12@126.com
 * @version 0.11
 * @date 2010-01-26
 * Copyright (c) 2010-2010 谢文浩
 */
/**
 * 
 * @param {Object}   xml 		xml数据ajax请求设置
 * @param {Object}   xsl 		xsl数据ajax请求设置
 * @param {String}   renderTo   视图覆盖或添加进的容器对象
 * @param {Function} fnCallBack 视图覆盖或添加完成后的回调函数
 * @param {Boolean}  isAppend   是否采用添加方式（默认采用覆盖方式即html()方法）
 */
yijs.air.view = function(xml,xsl,renderTo,fnCallBack,isAppend,fnChangeCallBack){
	var _xml = null;
	var _xsl = null;
	var isAppend = isAppend || false;
	if(xml != null && xsl != null) finish();
	function _ajax(options,fn){
		$.ajax({
			url: options.url,
			dataType:  options.dataType || "text",
			data : options.data || "",
			cache : options.cache || false,	
			success: function(data) {
				if(options.success) options.success.call(this,data);
				if(fn) fn.call(this,data);
			}
		});			
	}
	function finish(){	
		if(_xml == null){
			if(typeof xml == "object" && xml.url != null){
				_ajax(xml,function(data){_xml = data;_transform();});
			}else{
				_xml = xml;
				_transform();
			}		
		}
		if(_xsl == null){
			if(typeof xsl == "object" && xsl.url != null){
				_ajax(xsl,function(data){_xsl = data;_transform();});
			}else{
				_xsl = xsl;
				_xml == null && _transform();
			}		
		}		
	}
	
	function _transform(){
		if(_xml != null && _xsl != null){
			var result = yijs.air.view.transform(_xml,_xsl);
			if(fnChangeCallBack){
				fnChangeCallBack.call(this,renderTo,result);
			}else{
				!isAppend && $(renderTo).html(result) || $(renderTo).append(result);			
			}
			$(renderTo).data("xml",_xml).data("xsl",_xsl);	
			if(fnCallBack && typeof fnCallBack == "function") fnCallBack.call(this,xml,xsl); 
			return;
		}		
	}	
}
yijs.air.view.transform = function(xml,xsl){
		var domParser = new DOMParser();
		var xmlObject = typeof xml == "string" && domParser.parseFromString(xml,"text/xml")||xml;
		var xslObject = domParser.parseFromString(xsl,"text/xml");
		
		var xsltProcessor = new XSLTProcessor();
		xsltProcessor.importStylesheet(xslObject);
		var result = xsltProcessor.transformToFragment(xmlObject,document);
		
		var serializer = new XMLSerializer();
		return serializer.serializeToString(result);	
}
yijs.air.view.getLangXml = function(data){
	var lang = "";
	var xml = "";
	_each(data);
	xml = "<lang>"+lang+"</lang>";
	
	function _each(data){
		if(data && typeof data == "object"){
			$.each(data,function(key,value){
				if(typeof value == "object"){
					_each(value);
				}else{
					lang += "<"+key+">"+value+"</"+key+">";
				}
				
			})
		}		
	}
	
	return xml;
}
